import { exec } from 'child_process';
import { WebDriver } from 'selenium-webdriver';

// ===== 1. 新增屏幕尺寸获取 =====
async function getScreenSize(driver: WebDriver) {
  const { width, height } = await driver.manage().window().getRect();
  return { width, height };
}

// ===== 2. 优化滑动函数 =====
export async function performSmoothScroll(
  driver: WebDriver,
  deviceName: string,
  maxRetry = 3, // 默认重试3次
  strategy: 'standard' | 'long' = 'standard' // 下滑策略
) {
  // 动态计算坐标[1,2](@ref)
  const { width, height } = await getScreenSize(driver);
  const centerX = Math.floor(width / 2);
  
  let startY, endY;
  switch (strategy) {
    case 'long': // 长距离滑动（底部到顶部）
      startY = height - 100;
      endY = 100;
      break;
    default: // 标准下滑（70% -> 30%）
      startY = Math.floor(height * 0.7);
      endY = Math.floor(height * 0.3);
  }

  // 带重试机制的滑动[5](@ref)
  for (let attempt = 1; attempt <= maxRetry; attempt++) {
    console.log(`尝试下滑 #${attempt} [策略: ${strategy}]`);
    const success = await forceSwipeWithAdb(deviceName, centerX, startY, centerX, endY);
    
    if (success) {
      await new Promise(resolve => setTimeout(resolve, 1500)); // 滑动后等待[2](@ref)
      return true;
    } 
    
    console.warn(`滑动失败，准备重试（${attempt}/${maxRetry}）`);
    await resetAdbConnection(); // 重置ADB连接
  }
  
  throw new Error(`连续${maxRetry}次下滑失败`);
}

// ===== 3. 增强ADB滑动稳定性 =====
async function forceSwipeWithAdb(
  deviceName: string, 
  startX: number, 
  startY: number, 
  endX: number, 
  endY: number, 
  duration = 800
): Promise<boolean> {
  return new Promise(resolve => {
    const adbCmd = `adb -s ${deviceName} shell input swipe ${startX} ${startY} ${endX} ${endY} ${duration}`;
    console.log(`执行ADB滑动: ${adbCmd}`);

    exec(adbCmd, (error, _stdout, stderr) => {
      if (error || stderr) {
        console.error(`ADB错误: ${error?.message || stderr}`);
        resolve(false);
      } else {
        console.log("ADB滑动成功");
        resolve(true);
      }
    });
  });
}

// ===== 4. 防卡死机制（重置ADB连接）[7](@ref) =====
async function resetAdbConnection() {
  return new Promise(resolve => {
    console.log("重置ADB连接...");
    exec('adb kill-server && adb start-server', (err) => {
      if (err) console.error(`重置失败: ${err}`);
      setTimeout(resolve, 3000); // 等待3秒服务重启
    });
  });
}

